using System;
using System.Collections;
using LitJson;
using MTUnity.Utils;
using UnityEngine;
using UnityEngine.Experimental.GlobalIllumination;
using UnityEngine.Networking;

namespace Script.Net
{
    public class NetManager : MonoSingle<NetManager>
    {
        public  const string  LOGIN_URL = "http://wx.hechuangcd.com/api/TokenAuth/Authenticate";
        public  const string  SERVICE_URL = "http://wx.hechuangcd.com/api/services/app/";
        public string accessToken;
        IEnumerator LoginPost(string url, JsonData postBytes, Action<UnityWebRequest,JsonData> callback)
        {
            UnityWebRequest request = new UnityWebRequest(url, "POST");
            if (postBytes != null)
            {
                request.uploadHandler = (UploadHandler)new UploadHandlerRaw(System.Text.Encoding.Default.GetBytes(postBytes.ToJson()));
            }
            request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
 
            yield return request.Send();
            JsonData outData;
            Debug.Log("Status Code: " + request.responseCode);
            if (request.responseCode == 200)
            {
                string text = request.downloadHandler.text;
                outData = JsonMapper.ToObject(request.downloadHandler.text);
                Debug.Log(request.downloadHandler.text);
                accessToken = outData["result"]["accessToken"].ToString();
                Debug.LogWarning( accessToken);
                callback?.Invoke(request, outData["result"]);

            }
            else
            {
                outData = new JsonData();
                outData["error"] = request.error;
                callback?.Invoke(request, outData);
            }
        }
        
        IEnumerator _Get(string url, JsonData postBytes, Action<UnityWebRequest,MTJSONObject> callback)
        {
            UnityWebRequest request = new UnityWebRequest(url, "GET");
            request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            request.SetRequestHeader("Authorization", "Bearer " + accessToken);
            request.SetRequestHeader("Content-Type", "application/json");
            // request.SetRequestHeader("accessToken", accessToken);
            yield return request.Send();
            MTJSONObject outData;
            Debug.Log("Status Code: " + request.responseCode);
            if (request.responseCode == 200)
            {
                string text = request.downloadHandler.text;
                outData = MTJSON.Deserialize(request.downloadHandler.text);
                Debug.Log($"[Net] request {url} is Success {request.downloadHandler.text}");
                callback?.Invoke(request, outData["result"]);
            }
            else
            {
                outData = MTJSONObject.CreateDict();
                outData.Add("error", request.error);
                Debug.LogError($"[Net] request {url} is Error->({request.error})");
                // callback?.Invoke(request, outData);
            }
        }
        
        public void Login(string account, string passWord, Action<UnityWebRequest,JsonData> callback)
        {
            //使用litJson创建json格式的参数数据
            JsonData data = new JsonData();
            data["userNameOrEmailAddress"] = account;
            data["Password"] = passWord;
            data["rememberClient"] = true;
            
            StartCoroutine(LoginPost(LOGIN_URL, data, (req, retData) =>
            {
                if (!retData.ContainsKey("error"))
                {
                    retData["accessToken"] = accessToken;
                }
                callback?.Invoke(req, retData);
            } ));
        }
        
        public void GetCurrentWareHouserDaySumAsync(Action<UnityWebRequest,MTJSONObject> callback)
        {
            var url = SERVICE_URL + "WareHouserDaySum/GetCurrentWareHouserDaySumAsync";

            // 出入库的实时数据：                                {
            //     stockInNum：0，
            //     stockOutNum：0，
            //     currentStockNum：0，
            //     bufferStockNum：0，
            //     stockInEfficiency：0，
            //     stockOutEfficiency：0
            // }
            StartCoroutine(_Get(url, null, callback));
        }

 
        public void GetWareHouserOfDaysStatisAsync(int days, Action<UnityWebRequest,MTJSONObject> callback)
        {
            // http://119.23.174.202:8060/api/services/app/WareHouserDaySum/GetWareHouserOfDaysStatisAsync
            var url = SERVICE_URL + $"WareHouserDaySum/GetWareHouserOfDaysStatisAsync?days={days}";
            //天数（days，int）
            // 出入库近7-14天的效率                        [{     
            //     date:""                                                                                                                                                                                                    
            //     stockInEfficiency：0，
            //     stockOutEfficiency：0
            // }]           
            StartCoroutine(_Get(url, null, callback));
        }

        public void GetCurrentTHAsync(Action<UnityWebRequest,MTJSONObject> callback)
        {
            // 实时温度（当天？）                              [{
            //     collectionTime: "",
            //     wareHouserName: "",
            //     temperature: 0,
            //     humidity: 0
            // }]
            // http://119.23.174.202:8060/api/services/app/TemHumidityRecord/GetCurrentTHAsync
            var url = SERVICE_URL + "TemHumidityRecord/GetCurrentTHAsync";
            StartCoroutine(_Get(url, null, callback));
        }


        public void GetNearHoursTHDataAsync(int hours, Action<UnityWebRequest,MTJSONObject> callback)
        {
            //小时（hours，int）
            // 近12小时的温湿度数据（当前时间往前推12个小时）                                         [{
            //     collectionTime: "",
            //     wareHouserName: "",
            //     temperature:0 ,
            //     humidity: 0
            // }]
            //http://119.23.174.202:8060/api/services/app/TemHumidityRecord/GetNearHoursTHDataAsync
            var url = SERVICE_URL + $"TemHumidityRecord/GetNearHoursTHDataAsync?hours={hours}";
            StartCoroutine(_Get(url, null, callback));
        }
        
        public void GetNearHoursEnergyDataAsync(int sortLineId,int hours, Action<UnityWebRequest,MTJSONObject> callback){
            //小时（hours，int）
            // 近12小时的能耗数据（当天）                      [{
            //     collectionTime: "",
            //     sortLine: "线A",
            //     quantity: 0
            // }]
            //http://119.23.174.202:8060/api/services/app/EnergyDaySum/GetNearHoursEnergyDataAsync
            var url = SERVICE_URL + $"EnergyDaySum/GetNearHoursEnergyDataAsync?sortLineId={sortLineId}&hours={hours}";
            StartCoroutine(_Get(url, null, callback));
        }

        public void GetCurrentEnergyDataAaync(int sortLineId, Action<UnityWebRequest,MTJSONObject> callback)
        {
            // 实时能耗（当天）                                        [{
            //     collectionTime: "",
            //     sortLine: "",
            //     quantity: 0
            // }],
            // http://119.23.174.202:8060/api/services/app/EnergyDaySum/GetCurrentEnergyDataAsync
            var url = SERVICE_URL + $"EnergyDaySum/GetCurrentEnergyDataAsync?sortLineId={sortLineId}";
            StartCoroutine(_Get(url, null, callback));
        }

        public void GetCurrentSpotRoundOfSortingLineAsync(int sortLineId, Action<UnityWebRequest,MTJSONObject> callback)
        {
            // 当前巡查点（没有当前巡查点这样的数据）                                                                                   已巡查点                                        [{
            //     date: "",
            //     sortLine: "",
            //     count: 0
            // }]
            //http://119.23.174.202:8060/api/services/app/WorkOrder/GetCurrentSpotRoundOfSortingLineAsync
            var url = SERVICE_URL + $"WorkOrder/GetCurrentSpotRoundOfSortingLineAsync?sortLineId{sortLineId}";
            StartCoroutine(_Get(url, null, callback));
        }

        public void GetNearDaysSpotRoundOfSortingLineAsync(int days, int sortLineId,  Action<UnityWebRequest,MTJSONObject> callback)
        {
            //入参: 天数（days，int）
            // 近7日已巡查点趋势                                [{ 
            //     date: "",
            //     sortLine: "",
            //     count: 0
            // }]
            // http://119.23.174.202:8060/api/services/app/WorkOrder/GetNearDaysSpotRoundOfSortingLineAsync
            var url = SERVICE_URL + $"WorkOrder/GetNearDaysSpotRoundOfSortingLineAsync?sortLineId={sortLineId}&days={days}";
            StartCoroutine(_Get(url, null, callback));
        }

        public void GetCurrentSortLineDataAsync(int sortLineId,Action<UnityWebRequest,MTJSONObject> callback)
        {
            // 实时的分拣数据（当天）                             [{
            //     collectionTime: "",
            //     sortDate: "",
            //     sortLine: "",
            //     total: 0,
            //     complete: 0,
            //     durationSorting: 0.0,
            //     totalOrderNum: 0
            // }]
            //http://119.23.174.202:8060/api/services/app/SortDaySum/GetCurrentSortLineDataAsync
            var url = SERVICE_URL + $"SortDaySum/GetCurrentSortLineDataAsync?sortLineId={sortLineId}";
            StartCoroutine(_Get(url, null, callback));
        }
        
        public void GetNearDaySortLineTrendAsync(int days, long sortLineId,Action<UnityWebRequest,MTJSONObject> callback)
        {
            // 近几日的分拣数据                           [{
            //     collectionTime: "", 
            //     sortLineId: 2,
            //     complete: 0,
            //     durationSorting: 0,
            //     sortEfficiency: 0
            // }]
            //http://119.23.174.202:8060/api/services/app/SortDaySum/GetCurrentSortLineDataAsync
            var url = SERVICE_URL + $"SortDaySum/GetNearDaySortLineTrendAsync?days={days}&sortLineId={sortLineId}";
            StartCoroutine(_Get(url, null, callback));
        }
        
        public void GetSortLineLocationAsync(Action<UnityWebRequest,MTJSONObject> callback)
        {
            // 分拣线位置信息                                               {
            //     id: 0,
            //     code: "",
            //     name: ""
            // },
            //http://119.23.174.202:8060/api/services/app/SortDaySum/GetCurrentSortLineDataAsync
            var url = SERVICE_URL + "Location/GetSortLineLocationAsync";
            StartCoroutine(_Get(url, null, callback));
        }
        
        /// <summary>
        /// 能耗树
        /// </summary>
        /// <param name="callback"></param>
        public void GetDayTotalEnergyAsync(Action<UnityWebRequest,MTJSONObject> callback)
        {
            // 返回decimal类型的一个数据
            var url = SERVICE_URL + "EnergyDaySum/GetDayTotalEnergyAsync";
            StartCoroutine(_Get(url, null, callback));
        }
        
        /// <summary>
        /// 各分拣线汇总的分拣量（计划），当前已分拣量   
        /// </summary>
        /// <param name="callback"></param>
        public void GetDayTotalSortLIneDataAsync(Action<UnityWebRequest,MTJSONObject> callback)
        {
            // 各分拣线汇总的分拣量（计划），当前已分拣量                                            {
            //     total: 0,
            //     complete: 0
            // }
            //http://119.23.174.202:8060/api/services/app/SortDaySum/GetCurrentSortLineDataAsync
            var url = SERVICE_URL + "SortDaySum/GetDayTotalSortLIneDataAsync";
            StartCoroutine(_Get(url, null, callback));
        }

        /// <summary>
        /// 获取警告信息
        /// 分拣线预警信息
        /// </summary>
        /// <param name="callback"></param>
        public void GetWarningInfoOfSortLineAsync(Action<UnityWebRequest,MTJSONObject> callback)
        {
            // 分拣线预警信息                                 [{
            //     sortLineId: 0,
            //     code: "",
            //     equipment: "",
            //     content: "",
            //     time: "",
            //     warnLevelStr: ""
            // }]
            //http://119.23.174.202:8060/api/services/app/SortDaySum/GetCurrentSortLineDataAsync
            var url = SERVICE_URL + "SortLineBigScreen/GetWarningInfoOfSortLineAsync";
            StartCoroutine(_Get(url, null, callback));
        }
        
        /// <summary>
        /// 温湿度预警线              
        /// </summary>
        /// <param name="callback"></param>
        public void GetTHWarningInfoAsync(Action<UnityWebRequest,MTJSONObject> callback)
        {
            // 分拣线预警信息                                 [{
            //     sortLineId: 0,
            //     code: "",
            //     equipment: "",
            //     content: "",
            //     time: "",
            //     warnLevelStr: ""
            // }]
            //http://119.23.174.202:8060/api/services/app/SortDaySum/GetCurrentSortLineDataAsync
            var url = SERVICE_URL + "TemHumidityRecord/GetTHWarningInfoAsync";
            StartCoroutine(_Get(url, null, callback));
        }

        /// <summary>
        /// 实时工单数据
        /// </summary>
        /// <param name="callback"></param>
        public void GetDaySortLineWorkOrderByTypeAsync(Action<UnityWebRequest,MTJSONObject> callback)
        {
            // {
            //     loctionId: 0,
            //     num: 0,
            //     typeName: ""
            // }
            // loctionId: （分拣线Id，long）,
            // num: （数量，decimal）,
            // typeName: （工单类型，string）
            var url = SERVICE_URL + "WorkOrder/GetDaySortLineWorkOrderByTypeAsync";
            StartCoroutine(_Get(url, null, callback));
        }
        
    }
}